package com.hoperun.framework.ibatis.page;

import java.util.ArrayList;
import java.util.List;

public class PageUtils
{
  private static final int TWO = 2;

  public static int getFirstResult(int pageNumber, int pageSize)
  {
    if (pageSize <= 0)
    {
      throw new IllegalArgumentException("[pageSize] must great than zero");
    }
    return (pageNumber - 1) * pageSize;
  }

  public static List<Integer> generateLinkPageNumbers(int currentPageNumber, int lastPageNumber, int count)
  {
    int avg = count / 2;

    int startPageNumber = currentPageNumber - avg;
    if (startPageNumber <= 0)
    {
      startPageNumber = 1;
    }

    int endPageNumber = startPageNumber + count - 1;
    if (endPageNumber > lastPageNumber)
    {
      endPageNumber = lastPageNumber;
    }

    if (endPageNumber - startPageNumber < count)
    {
      startPageNumber = endPageNumber - count;
      if (startPageNumber <= 0)
      {
        startPageNumber = 1;
      }
    }

    List result = new ArrayList();
    for (int i = startPageNumber; i <= endPageNumber; i++)
    {
      result.add(Integer.valueOf(i));
    }
    return result;
  }

  public static int computeLastPageNumber(int totalElements, int pageSize)
  {
    int result = 1;
    if (totalElements % pageSize == 0)
    {
      result = totalElements / pageSize;
    }
    else
    {
      result = totalElements / pageSize + 1;
    }
    return result;
  }

  public static int computePageNumber(int pageNumber, int pageSize, int totalElements)
  {
    if (pageNumber <= 1)
    {
      return 1;
    }
    if ((2147483647 == pageNumber) || (pageNumber > computeLastPageNumber(totalElements, pageSize)))
    {
      return computeLastPageNumber(totalElements, pageSize);
    }
    return pageNumber;
  }
}